#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QMouseEvent>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QMessageBox>
#include <QPainter>


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setFixedSize(size());
    this->setWindowFlags(Qt::FramelessWindowHint);

    weaListInit();
    weaImgMapInit();
    /*
    weaTimer = new QTimer(this);
    connect(weaTimer, &QTimer::timeout, this, [=](){
       weaDateTime = QDateTime::currentDateTime();
       QString timeFormat = QString("%1:%2:%3").arg(weaDateTime.time().hour(), 2, 10, QChar('0'))
                                               .arg(weaDateTime.time().minute(), 2, 10, QChar('0'))
                                               .arg(weaDateTime.time().second(), 2, 10, QChar('0'));
        ui->part2_label_realTime->setText(timeFormat);
    });
    weaTimer->start(1000);
*/
    updateThread = new timeThread(this);
    connect(updateThread, &timeThread::timeRefresh, this, [=](){
        QDateTime weaDateTime = QDateTime::currentDateTime();
        QString timeFormat = weaDateTime.toString("HH:mm:ss ap");
        ui->part2_label_realTime->setText(timeFormat);
    });
    updateThread->start();

    this->installEventFilter(this);
    ui->part5_widget1->installEventFilter(this);
    ui->part5_widget2->installEventFilter(this);

    closeMenu = new QMenu(this);
    closeMenu->addAction(QIcon(QPixmap(":/res/Close.png")), tr("关闭"));
    connect(closeMenu, &QMenu::triggered, this, &Widget::on_closeWindow);

    manager = new QNetworkAccessManager(this);
    connect(manager, &QNetworkAccessManager::finished, this, &Widget::on_replyFinished);
    urlAddr = "http://gfeljm.tianqiapi.com/api?unescape=1&version=v9&appid=49531715&appsecret=g1Dgfekc";
    connect(this, &Widget::run_Init, this, [=](){
        manager->get(QNetworkRequest(QUrl(urlAddr)));
    });
    emit run_Init();
}


Widget::~Widget()
{
    delete ui;
}


bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if((watched == ui->part5_widget1) && (event->type() == QEvent::Paint))
    {
        drawTempLineH();
        return true;
    }
    if((watched == ui->part5_widget2) && (event->type() == QEvent::Paint))
    {
        drawTempLineL();
        return true;
    }
    if(event->type() == QEvent::MouseButtonPress)
    {
        QMouseEvent *mouse = dynamic_cast<QMouseEvent*>(event);
        if(mouse->button() == Qt::LeftButton)
        {
            mouseStatus = leftPress;
            posOffset = mouse->globalPos() - this->pos();

        }else{
            mouseStatus = rightPress;
            closeMenu->exec(mouse->globalPos());
        }
        return true;
    }
    if(event->type() == QEvent::MouseMove)
    {
        QMouseEvent *mouse = dynamic_cast<QMouseEvent*>(event);
        if(mouseStatus == leftPress)
        {
            this->move(mouse->globalPos() - posOffset);
        }
        return true;
    }
    return QWidget::eventFilter(watched, event);
}


void Widget::getDataFromUrl(QNetworkReply *reply)
{
    QByteArray rawData = reply->readAll();
    QJsonDocument jsonDoc = QJsonDocument::fromJson(rawData);
    if(!jsonDoc.isNull() && jsonDoc.isObject())
    {
        QJsonObject jsonObj = jsonDoc.object();
        ui->part2_label_city->setText(jsonObj["city"].toString());
        if(jsonObj.contains("data") && jsonObj["data"].isArray())
        {
            QJsonArray jsonArr = jsonObj["data"].toArray();
            for(int i=0; i<jsonArr.size(); i++)
            {
                if(jsonArr[i].isObject())
                {
                    QJsonObject dataObj = jsonArr[i].toObject();
                    day[i].jsonDate = dataObj["date"].toString();
                    day[i].jsonWeek = dataObj["week"].toString();
                    day[i].jsonWea = dataObj["wea"].toString();
                    day[i].jsonTem = dataObj["tem"].toString();
                    day[i].jsonTemH = dataObj["tem1"].toString();
                    day[i].jsonTemL = dataObj["tem2"].toString();
                    day[i].jsonHum = dataObj["humidity"].toString();
                    day[i].jsonWin = dataObj["win"].toArray()[0].toString();
                    day[i].jsonWinSpeed = dataObj["win_speed"].toString();
                    day[i].jsonAirLevel = dataObj["air_level"].toString();
                    day[i].jsonAirTips = dataObj["air_tips"].toString();
                }
            }
        }
        if(jsonObj.contains("aqi") && jsonObj["aqi"].isObject())
        {
            QJsonObject aqiObj = jsonObj["aqi"].toObject();
            ui->part3_label_pmVal->setText(aqiObj["pm25"].toString());
        }
    }
    updateUiDisplay();
}


void Widget::updateUiDisplay()
{
    ui->part1_label_time->setText(day[0].jsonDate + " " + day[0].jsonWeek);

    ui->part2_label_temp->setText(day[0].jsonTem);
    ui->part2_label_wType->setText(day[0].jsonWea);
    ui->part2_label_tempRange->setText(day[0].jsonTemL + " ~ " + day[0].jsonTemH + "℃");

    ui->part3_label_tips->setText(day[0].jsonAirTips);
    ui->part3_label_fx->setText(day[0].jsonWin);
    ui->part3_label_sdVal->setText(day[0].jsonHum);
    ui->part3_label_airVal->setText(day[0].jsonAirLevel);

    for(int i=0; i<7; i++)
    {
        listWeek[i]->setText(day[i].jsonWeek);
        listWeek[0]->setText("今天");
        listWeek[1]->setText("明天");
        listWeek[2]->setText("后天");

        QStringList dateList = day[i].jsonDate.split("-");
        listDate[i]->setText(dateList[1] + "-" + dateList[2]);

        int weaIndex = day[i].jsonWea.indexOf("转");
        QString weaTmp = day[i].jsonWea.left(weaIndex);
        QPixmap weaImg = QPixmap(weaImgMap.find(weaTmp).value());
        weaImg = weaImg.scaled(ui->part4_label_day1Img->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        listWeaImg[i]->setPixmap(weaImg);
        if(i == 0)
        {
            ui->part2_label_wImp->setPixmap(weaImg);
        }

        listWeaType[i]->setText(day[i].jsonWea);

        listAirLevel[i]->setText(day[i].jsonAirLevel);
        if(day[i].jsonAirLevel == "优")
        {
            listAirLevel[i]->setStyleSheet("background-color: rgb(127, 188, 93); color: rgb(255, 255, 255); border-radius: 5px;");
        }
        else if(day[i].jsonAirLevel == "良")
        {
            listAirLevel[i]->setStyleSheet("background-color: rgb(255, 170, 0); color: rgb(255, 255, 255); border-radius: 5px;");
        }else{
            listAirLevel[i]->setStyleSheet("background-color: rgb(255, 0, 0); color: rgb(255, 255, 255); border-radius: 5px;");
        }

        listWinDir[i]->setText(day[i].jsonWin);

        int winIndex = day[i].jsonWinSpeed.indexOf("转");   //没有找到的话就返回-1,找到的话就返回index
        QString winTmp =  day[i].jsonWinSpeed.left(winIndex);  //如果index大于字符串长度或者小于0，则返回字符串本身，否则返回index左边的字符串
        listWinSpeed[i]->setText(winTmp);
        if(i == 0)
        {
            ui->part3_label_fl->setText(winTmp);
        }
    }
    repaint();   //这个repaint必须要有不然无法自动触发绘画事件。只能通过手动触发！！！
}


void Widget::weaListInit()
{
    for(int i=1; i<8; i++)
    {
        QString cWeek = QString("part4_label_day%1").arg(i);
        QLabel *fWeek = findChild<QLabel*>(cWeek);
        listWeek.append(fWeek);

        QString cDate = QString("part4_label_day%1Val").arg(i);
        QLabel *fDate = findChild<QLabel*>(cDate);
        listDate.append(fDate);

        QString cWeaImg = QString("part4_label_day%1Img").arg(i);
        QLabel *fWeaImg = findChild<QLabel*>(cWeaImg);
        listWeaImg.append(fWeaImg);

        QString cWeaType = QString("part4_label_day%1Type").arg(i);
        QLabel *fWeaType = findChild<QLabel*>(cWeaType);
        listWeaType.append(fWeaType);

        QString cAirLevel = QString("part4_label_day%1air").arg(i);
        QLabel *fAirLevel = findChild<QLabel*>(cAirLevel);
        listAirLevel.append(fAirLevel);

        QString cWinDir = QString("part6_label_day%1fx").arg(i);
        QLabel *fWinDir = findChild<QLabel*>(cWinDir);
        listWinDir.append(fWinDir);

        QString cWinSpeed = QString("part6_label_day%1fl").arg(i);
        QLabel *fWinSpeed = findChild<QLabel*>(cWinSpeed);
        listWinSpeed.append(fWinSpeed);
    }
}


void Widget::weaImgMapInit()
{
    weaImgMap.insert("暴雪",":/res/type/BaoXue.png");
    weaImgMap.insert("暴雨",":/res/type/BaoYu. png");
    weaImgMap.insert("暴雨到大暴雨",":/res/type/BaoYuDaoDaBaoYu.png");
    weaImgMap.insert("大暴雨",":/res/type/DaBaoYu.png");
    weaImgMap.insert("大暴雨到特大暴雨",":/res/type/DaBaoYuDaoTeDaBaoYu.png");
    weaImgMap.insert("大到暴雪",":/res/type/DaDaoBaoXue.png");
    weaImgMap.insert("大雪",":/res/type/DaXue.png");
    weaImgMap.insert("大雨",":/res/type/DaYu.png");
    weaImgMap.insert("冻雨",":/res/type/DongYu.png");
    weaImgMap.insert("多云",":/res/type/DuoYun.png");
    weaImgMap.insert("浮尘",":/res/type/FuChen.png");
    weaImgMap.insert("雷阵雨",":/res/type/LeiZhenYu.png");
    weaImgMap.insert("雷阵雨伴有冰雹",":/res/type/LeiZhenYuBanYouBingBao.png");
    weaImgMap.insert("霾",":/res/type/Mai.png");
    weaImgMap.insert("强沙尘暴",":/res/type/QiangShaChenBao.png");
    weaImgMap.insert("晴",":/res/type/Qing.png");
    weaImgMap.insert("沙尘暴",":/res/type/ShaChenBao.png");
    weaImgMap.insert("特大暴雨",":/res/type/TeDaBaoYu.png");
    weaImgMap.insert("undefined",":/res/type/undefined.png");
    weaImgMap.insert("雾",":/res/type/Wu.png");
    weaImgMap.insert("小到中雪",":/res/type/XiaoDaoZhongXue.png");
    weaImgMap.insert("小到中雨",":/res/type/XiaoDaoZhongYu.png");
    weaImgMap.insert("小雪",":/res/type/XiaoXue.png");
    weaImgMap.insert("小雨",":/res/type/XiaoYu.png");
    weaImgMap.insert("大雾",":/res/type/DaWu.png");
    weaImgMap.insert("扬沙",":/res/type/YangSha.png");
    weaImgMap.insert("阴",":/res/type/Yin.png");
    weaImgMap.insert("浓雾",":/res/type/NongWu.png");
    weaImgMap.insert("雨夹雪",":/res/type/YuJiaXue.png");
    weaImgMap.insert("阵雪",":/res/type/ZhenXue.png");
    weaImgMap.insert("阵雨",":/res/type/ZhenYu.png");
    weaImgMap.insert("中到大雪",":/res/type/ZhongDaoDaXue.png");
    weaImgMap.insert("中到大雨",":/res/type/ZhongDaoDaYu.png");
    weaImgMap.insert("中雪",":/res/type/ZhongXue.png");
    weaImgMap.insert("中雨",":/res/type/ZhongYu.png");
    weaImgMap.insert("强浓雾",":/res/type/QiangNongWu.png");
    weaImgMap.insert("特强浓雾",":/res/type/TeQiangNongWu.png");
    weaImgMap.insert("中度霾",":/res/type/ZhongDuMai.png");
    weaImgMap.insert("严重霾",":/res/type/YanZhongMai.png");
}


void Widget::drawTempLineH()
{
    QPainter painter(ui->part5_widget1);
    painter.setBrush(QBrush(QColor(207, 138, 0, 255)));
    painter.setPen(QPen(QBrush(QColor(207, 138, 0, 255)), 3));

    int tempAve;
    int posOffset;
    int sum = 0;
    int mid = ui->part5_widget1->height()/2;
    for(int i=0; i<7; i++)
    {
        sum += day[i].jsonTemH.toInt();
    }
    tempAve = sum/7;
    QPoint point[7];
    for(int i=0; i<7; i++)
    {
        point[i].setX(listAirLevel[i]->x()-12 + listAirLevel[i]->width()/2);
        posOffset = (day[i].jsonTemH.toInt() -tempAve)*3;
        point[i].setY(mid - posOffset);
        painter.drawEllipse(point[i], 5, 5);
        QFont font("Arial", 11);
        font.setBold(true);
        painter.setFont(font);
        painter.drawText(QPoint(point[i].x()-15, point[i].y()-15), day[i].jsonTemH + "°");
    }
    for(int i=0; i<6; i++)
    {
        painter.drawLine(point[i], point[i+1]);
    }
}


void Widget::drawTempLineL()
{
    QPainter painter(ui->part5_widget2);
    painter.setBrush(QBrush(QColor(0, 197, 197, 255)));
    painter.setPen(QPen(QBrush(QColor(0, 197, 197, 255)), 3));

    int tempAve;
    int posOffset;
    int sum = 0;
    int mid = ui->part5_widget2->height()/2;
    for(int i=0; i<7; i++)
    {
        sum += day[i].jsonTemL.toInt();
    }
    tempAve = sum/7;
    QPoint point[7];
    for(int i=0; i<7; i++)
    {
        point[i].setX(listAirLevel[i]->x()-12 + listAirLevel[i]->width()/2);
        posOffset = (day[i].jsonTemL.toInt() -tempAve)*3;
        point[i].setY(mid - posOffset);
        painter.drawEllipse(point[i], 5, 5);
        QFont font("Arial", 11);
        font.setBold(true);
        painter.setFont(font);
        painter.drawText(QPoint(point[i].x()-15, point[i].y()-15), day[i].jsonTemL + "°");
    }
    for(int i=0; i<6; i++)
    {
        painter.drawLine(point[i], point[i+1]);
    }
}


void Widget::on_closeWindow()
{
    //    qDebug() << "actiton trigged~~~";
    this->close();
}


void Widget::on_replyFinished(QNetworkReply *reply)
{
    if(reply->error() == QNetworkReply::NoError)
    {
        getDataFromUrl(reply);
    }
    else
    {
        qDebug() << reply->error();
        return;
    }
}


void Widget::on_part1_pushButton_sButton_clicked()
{
    //          qDebug() << "search button clicked ~~";
    QString tmp = cityMap.getCityInfoFromMap(ui->part1_lineEdit_sFrame->text());
    if(tmp != NULL)
    {
        QString cUrl = urlAddr + "&cityid=" + tmp;
        manager->get(QNetworkRequest(QUrl(cUrl)));
    }else{
        QMessageBox msgBox;
        msgBox.setWindowTitle("提示");
        msgBox.setIcon(QMessageBox::Question);
        msgBox.setText("请输入正确的城市名^_^");
        //              msgBox.setStyleSheet("QPushButton{background-color: rgb(255, 0, 0)}");
        msgBox.exec();
    }
}


void Widget::on_part1_lineEdit_sFrame_returnPressed()
{
    on_part1_pushButton_sButton_clicked();
}

